package com.cwx.dao;

import com.cwx.pojo.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
public interface BlogRepository extends JpaRepository<Blog,Long>, JpaSpecificationExecutor<Blog> {

    //按照更新时间查出最新的前几篇博客
    @Query("select t from Blog  t")
    List<Blog> findTop(Pageable pageable);

    //全局查询博客
    @Query("select b from Blog b where b.title like ?1 or b.content like ?1")
    Page<Blog> findBySearch(String query, Pageable pageable);


    //点击博客，浏览次数加一
    @Transactional  //添加事务
    @Modifying  //修改操作
    @Query("update Blog  b set b.views = b.views + 1 where b.id = ?1")
    int updateViews(Long id);

    //查询出所有的博客 都有哪些博客
    @Query(value = "select DATE_FORMAT(b.update_time,'%Y') as year  from t_blog b GROUP BY DATE_FORMAT(b.update_time,'%Y') ORDER BY year desc ",nativeQuery = true)
    List<String> findGroupYear();

    //查询对应年份有哪些博客
    @Query(value = "select * from t_blog b where DATE_FORMAT(b.update_time,'%Y') = ?1 ",nativeQuery = true)
    List<Blog> findByYear(String year);
}
